<?php
namespace app\shop\controller\api;

use app\shop\library\ApiController;
use app\shop\library\Member as ShopMember;

class Outside extends ApiController{
    
    public function onLogin(){
        $mobile = $this->post('mobile',$this->check('手机号')->type('string')->reg(ShopMember::$mobileReg)->required());
        $password = $this->post('password',$this->check()->type('string')->required());
        $type  = $this->post('type',$this->check()->type('string')->required());
        $member = $this->model('Member');
        $data = $member->where('mobile',$mobile)->getRow();
        if($data){

            if ($data['password'] == ShopMember::makePassword($password) ){

                $update['last_login_type'] = $type;
                $update['last_login_time'] = time();

                $member->updateId($data['member_id'],$update);
                
                return [
                    'token'=>ShopMember::encodeToken($data),
                    'info'=>ShopMember::formatFront($data)
                ];
                
            }else{
                throw new \Exception('手机号或者密码错误');    
            }

        }else{
            throw new \Exception('手机号或者密码错误');
        }
        
    }

    public function onRegister(){

        $mobile = $this->post('mobile',$this->check('手机号')->type('string')->reg(ShopMember::$mobileReg)->required());
        $code = $this->post('code',$this->check()->type('string')->required());
        $nickname = $this->post('nickname',$this->check()->type('string')->required());
        $password = $this->post('password',$this->check()->type('string')->required());
        

        $member = $this->model('Member');

        //验证手机号
        if ($member->where('mobile',$mobile)->count()>0){
            throw new \Exception('手机号已存在');
        }

        $data = [
            'mobile'=>$mobile,
            'nickname'=>$nickname,
            'password'=>ShopMember::makePassword($password),
            'level_id'=>0,
            'last_login_time'=>time(),
            'reg_time'=>time()
        ];

        if ($member_id = $member->insert($data)){
            $info = $member->getId($member_id);
            return [
                'token'=>ShopMember::encodeToken($info),
                'member_id'=>$member_id,
                'info'=>ShopMember::formatFront($info)
            ];
        }else{
            throw new \Exception('注册失败');
        }
    }


    //发送验证码
    public function onSendCode(){
        $mobile = $this->post('mobile',$this->check('手机号')->type('string')->reg(ShopMember::$mobileReg)->required());

        $cache = $this->cache();

        $cacheKey = 'verification_code_'.$mobile;
        if ($cache->exists($cacheKey)){
            throw new \Exception('验证码已发送，请稍后再试');
        }else{
            $code = rand(1000,9999);
            //TODO 等待短信接口
        
        }
    }
}